package leetcode.剑指offer;

import java.util.*;

public class 从上到下打印二叉树32_2 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null)
            return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        Map<TreeNode, Integer> map = new HashMap<>();
        queue.add(root);
        map.put(root, 1);
        int now = 1;
        List<Integer> nowRow = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();
            int count = map.get(treeNode);
            if(count>now){
                list.add(nowRow);
                nowRow = new ArrayList<>();
                now++;
            }
            nowRow.add(treeNode.val);
            if (treeNode.left != null) {
                map.put(treeNode.left, count + 1);
                queue.add(treeNode.left);
            }
            if (treeNode.right != null) {
                map.put(treeNode.right, count + 1);
                queue.add(treeNode.right);
            }
        }
        list.add(nowRow);
        return list;

    }

    public static void main(String[] args) {
        int[] pre = new int[]{3,9,20,15,7};
        int[] in = new int[]{9,3,15,20,7};
        TreeNode node = new Solution().buildTree(pre,in);
        List<List<Integer>> list = new 从上到下打印二叉树32_2().levelOrder(node);
        System.out.println(list);

    }
}
